<template>
  <!--核收开窗-->
  <el-dialog v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" title="批量录入条码" :visible.sync="dialogCollectVisible" @close="CollectClose()" v-if="dialogCollectVisible" width="1100px">
      <div style="width:100%;text-align:right">
          <table style="cellspacing: 5px" class="collectbtntable">
              <tr>
                  <td>生成时间</td>
                  <td>
                      <el-date-picker v-model="search_begindt" :clearable="false" type="datetime" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss" style="width: 170px" :picker-options="pickerOptions"> </el-date-picker>
                      <!-- <el-date-picker v-model="collectselectdate" value-format="yyyy-MM-dd HH:mm:ss" style="width:100%" :picker-options="pickerOptions" :clearable="false"></el-date-picker> -->
                      至
                      <el-date-picker v-model="search_enddt"   type="datetime" :clearable="false" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss" style="width: 170px" :picker-options="pickerOptions"> </el-date-picker>
                  </td>
                  <td align="right">送检医院</td>
                  <td>
                  <rm-ddl-common  datatype="hospital" dataname="医院" v-model="search_hoscode" width="100%"></rm-ddl-common>
                  </td>
                  <td>
                      <el-button @click="querydata" style="margin-bottom: 5px" type="primary">查询</el-button>
                      <el-button @click="importPackageBarcode" style="margin-bottom: 5px">导入包条码</el-button>
                      <el-button @click="confirmInput" style="margin-bottom: 5px">确定录入</el-button>
                      <el-button @click="CollectClose" style="margin-bottom: 5px">退出</el-button>
                  </td>

              </tr>
              <tr>
                  <td> 条码号范围 </td>
                  <td colspan="2">
                       <el-input v-model.trim="search_barcodes"  clearable style="width: 100%"></el-input>
                  </td>
                  <td><label style="color: #c7c7c7;">条码号可以输入:12345,123456,100000-666666的格式</label></td>

              </tr>
          </table>
      </div>
      <table style="margin-top:10px">
          <tr>
              <td style="font-weight:bold;font-size: 14px">
                  起始标本编号
              </td>
              <td>
                   <el-input v-model="collectsampleno"  ref="collectspec" class="collectspec"></el-input>
              </td>
              <td>
                  报告单元
              </td>
              <td>
                  <rm-ddl-rptunit :prgno="PRGNO" defaultflag="1" v-model="collectrptunitid" width="160px" :clearable="false" @change="collectrptunitidchange" ref="collectrptunit"></rm-ddl-rptunit>
              </td>
              <td>
                  标本日期
              </td>
              <td>
                  <el-date-picker v-model="collectselectdate" value-format="yyyy-MM-dd HH:mm:ss" style="width:100%" :picker-options="pickerOptions" :clearable="false"></el-date-picker>
              </td>
          </tr>
      </table>

      <div style="height: 400px">
          <div style="height:100%">
              <vxe-table :data.sync="MasterDataDisplay"
                          :sort-config="{trigger: 'cell'}"
                          :edit-config="{trigger: 'click', mode: 'cell',showStatus: true}"
                          :mouse-config="{selected: true}"
                          :select-config="selectConfig"
                          :keyboard-config="keyConfig" border
                          height="auto"
                          highlight-current-row
                          highlight-hover-row
                          ref="xTableCollect" resizable highlight-hover-column show-header-overflow="tooltip" show-overflow="tooltip" header-align="center" align="center" size="mini" stripe width="auto" :row-class-name="xTableCollect_rowClass"  >
                  <vxe-table-column type="selection" width="30px"></vxe-table-column>
                  <vxe-table-column field="sampleno" title="标本编号" key="sampleno" width="60px" sortable :sort-width="20"></vxe-table-column>
                  <vxe-table-column field="barcode" title="条码号" key="barcode" width="100px"></vxe-table-column>
                  <vxe-table-column field="emer_flag" title="急" key="emer_flag" width="30px" sortable>
                      <template v-slot="{ row }">
                          <span style="color:red" v-if="row.emer_flag>0">急</span>
                      </template>
                  </vxe-table-column>
                  <vxe-table-column field="pat_name" title="病人" key="pat_name" width="60px" sortable>
                      <template v-slot="{ row }">
                          <div class="parent-row" v-if="row.sflag == -1 || row.sflag == 2">
                              <span class="parent-row-name">{{row.pat_name}}</span>
                          </div>
                          <div v-else>{{row.pat_name}}</div>
                      </template>
                  </vxe-table-column>
                  <vxe-table-column field="pat_no" title="病人号" key="pat_no" width="100px"></vxe-table-column>
                  <vxe-table-column field="pat_typename" title="病人类型" key="pat_typename" width="60px"></vxe-table-column>
                  <vxe-table-column field="specimen_name" title="标本类型" key="specimen_name" width="80px" sortable></vxe-table-column>
                  <vxe-table-column field="sample_items" title="申请项目" key="sample_items" width="200px" align="left" header-align="center"></vxe-table-column>
                  <vxe-table-column field="req_deptname" title="科室" key="req_deptno" width="120px" sortable></vxe-table-column>
                  <vxe-table-column field="req_bedno" title="床号" key="req_bedno" width="60px" sortable></vxe-table-column>
              </vxe-table>
          </div>
      </div>
      <el-dialog v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" title="输入包条码" :visible.sync="ImportPackageBarcodeVisible">
          <div>
              <el-input v-model="packagebarcode" placeholder="输入包条码"></el-input>
          </div>
          <div style="text-align: right">
              <el-button @click="ConfirmBarcode()">确 定</el-button>
              <el-button @click="CancelBarcode()">取 消</el-button>
          </div>
      </el-dialog>
      <el-dialog v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" :visible.sync="dialogMsgListVisible" :destroy-on-close="true" title="错误消息一览"  top="5vh" width="450px" @close="dialogMsgListVisible = false">
          <div style="height: 530px">
              <vxe-table :data="tableDataMsgDialog" :select-config="selectConfig" :keyboard-config="keyConfig" height="100%" highlight-current-row highlight-hover-row ref="xTableDialogMsg" resizable highlight-hover-column border show-header-overflow="tooltip" show-overflow="tooltip" header-align="center" size="mini" stripe width="auto">
                  <vxe-table-column type="index" title="NO." width="40" align="center"></vxe-table-column>
                  <vxe-table-column field="content" title="提示内容" width="400" sortable header-align="center" ></vxe-table-column>
              </vxe-table>
          </div>
          <div style="text-align: right;margin-top:5px;">
              <el-button @click="dialogMsgListVisible = false">退出</el-button>
          </div>
      </el-dialog>
  </el-dialog>
</template>

<script>
import XE from "xe-utils";
export default {
  name: "rmLabreportBatchcollect",
  data() {
      return {
          PRGNO: "",
          //是否异步处理方式
          isasync: false,
          pickerOptions: {
              shortcuts: [
                  {
                      text: "今天",
                      onClick(picker) {
                          picker.$emit("pick", XE.toDateString(new Date(), "yyyy-MM-dd 00:00:00"));
                      }
                  }
              ]
          }, //日期配置将时间切换到当天
          rptunitid: 0,
          BeforePatient: {},
          dialogCollectVisible: false,
          collectselectdate: "",
          collectrptunitid: 0,
          collectsampleno: "1",
          CollectSpecType: "",
          previousPatient: {},
          temppreviousPatient: {},
          copylabellty: "1",
          alertcannoitem: false,
          CollectNum: 0,
          CollectErrNum: 0,
          batchinputshownoseg: false,
          MasterData: [],
          MasterDataDisplay: [],
          //主数据异步同步标志
          MasterDataSyncFlag: false,
          selectConfig: { tigger: "row" },
          keyConfig: {
              isDel: true,
              isTab: true,
              isEdit: true
          },
          batchbarcodeonlytoday: "",
          collectbarcodeholder: "请扫描条码",
          tableColumnBatch: [],
          tableDataBatch: [],
          //扫码后台进程运行标志
          timeoutrunning: false,
          lasttxtbarcode: "",
          Options: {}, //选项

          collectmustconfirm: true, //提醒模式
          search_begindt:"",
          search_enddt:"",
          search_hoscode:"",//送检医院
          search_barcodes:"",// 条码号范围
          ImportPackageBarcodeVisible: false,
          packagebarcode: "",//包条码,
          tableDataMsgDialog: [],
          dialogMsgListVisible: false,
      };
  },
  watch: {

  },
  created() {
      let syncstr = this.$tool.getLocalConfig("lis310_async");
      if (syncstr) {
          this.isasync = syncstr == "Y";
      }
  },
  methods: {
      //从服务器返回的结果处理
      DealEvent(that, barcodestr, res, t_issync, csampleno, response) {
          that.$parent
              .ErrorListDeal(res.msg, res.flag, 0)
              .then(() => {
                  that.CollectSave(that, 1, barcodestr, csampleno, response); //type=0 错误消息 type=1 确认消息
              })
              .catch(() => {
                  that.CollectSave(that, 0, barcodestr, csampleno, response);
              });
      },
      RePrintBarcode(barcode) {
          console.log("bbb", barcode, this.Options.lisbarstyle);
          if (barcode && barcode != "") {
              if (!this.Options.lisbarstyle || this.Options.lisbarstyle == "") {
                  this.$alert("没有维护条码样式!", "提示");
              } else {
                  this.$pub.printbarcode(this, barcode, "1", this.Options.lisbarstyle, "", "1");
              }
          }
      },
      CollectSave(that, type, barcodestr, csampleno, response) {
          //type=0 错误消息 type=1 确认消息
          let index = that.MasterData.findIndex(eitem => eitem.barcode == barcodestr && eitem.sampleno == csampleno);
          if (type) {
              //TODO 条码录入
              that.$tool
                  .request({
                      url: "LIS/LIS3/LIS310",
                      method: "post",
                      data: {
                          action: "savecollectbarcode",
                          rptunitid: that.collectrptunitid,
                          barcode: barcodestr,
                          sampledate: that.collectselectdate,
                          sampleno: csampleno,
                          reportuser: that.exactusernoreport,
                          specimen_code: that.CollectSpecType,
                          alertcannoitem: that.alertcannoitem ? "1" : "0"
                      }
                  })
                  .then(res => {
                      if (res.flag == "1") {
                          if (that.isasync) {
                              that.MasterData[index] = that.MasterData[index].res.report;
                              if (index && index > -1) that.MasterData[index].sflag = 0; // mod by yangliang 2021-05-23  应该改成0 表示完成了吧
                              that.MasterData = that.MasterData.slice(0);
                              that.CollectErrNum -= 1;
                              let row = that.$refs.xTableCollect.tableFullData[index];
                              that.$refs.xTableCollect.setCurrentRow(row);
                          } else {
                              that.temppreviousPatient.reportid = res.reportid;
                              that.previousPatient = that.temppreviousPatient;
                              that.MasterData.splice(0, 0, that.temppreviousPatient);
                              that.$refs.xTableCollect.setCurrentRow(that.temppreviousPatient);
                              that.collectsampleno = res.nextsmpno;
                              that.CollectNum = that.MasterData.length;

                          }
                          try {
                              if (that.Options.inputprintgermsheet > 0) {
                                  if (that.Options.germsheetid > 0) {
                                      if (res && res.reportid) {
                                          that.$pub.printgermsheet(that, res.reportid, that.Options.germsheetid, "1");
                                      }
                                  } else {
                                      that.$message.error("没有维护细菌流程单样式！");
                                  }
                              }

                              // 添加录入条码后自动打印条码的判断
                              if (response.barcode && response.barcodeprintcount && response.barcodeprintcount > 0) {
                                  for (let i = 0; i < response.barcodeprintcount; i++) {
                                      this.RePrintBarcode(response.barcode);
                                  }
                              }
                              //end
                          } catch (e) {
                              console.log("ee", e);
                          }
                      } else {
                          let msg = res.msg;
                          if (!msg) {
                              msg = "条码核收失败，核收过程发生错误！";
                          }
                          that.$alert(msg).then(() => {
                              if (index && index > -1) that.MasterData[index].sflag = 2;
                              that.CollectErrNum -= 1;

                          });
                      }
                  })
                  .catch(error => {
                      console.log("errorerror", error);
                      that.$alert("条码核收失败，核收过程发生异常！").then(() => {});
                  });
          } else {
              if (this.isasync) {
                  that.MasterData[index].sflag = 2;
                  that.CollectErrNum -= 1;
                  let row = that.$refs.xTableCollect.tableFullData[index];
                  that.$refs.xTableCollect.setCurrentRow(that.MasterData[index]);

              } else {

              }
          }
      },

      //核收项目，从父级调用，入口
      CollectDeal(prgno, rptunitid, selectdate, specno, batchbarcodeonlytoday, options) {
          let that = this;
          that.PRGNO = prgno;
          this.Options = options;
          that.$tool
              .request({
                  url: "LIS/LIS3/LIS310",
                  method: "post",
                  data: {
                      action: "getreceivesampleno",
                      rptunitid: rptunitid,
                      sampledate: selectdate,
                      sampleno: specno
                  }
              })
              .then(res => {
                  if (res.flag == 1) {
                      that.dialogCollectVisible = true;
                      that.collectrptunitid = rptunitid - 0;
                      //that.collectsampleno = res.sampleno;
                      that.collectsampleno = "";
                      that.collectselectdate = XE.clone(selectdate, true);
                      that.search_begindt = this.$pub.InitDateTime2(0).datefrom;
                      that.search_enddt =this.$pub.InitDateTime2(0).dateto;
                  } else {
                      that.$parent.ErrorListDeal(res.msg, res.flag);
                  }
              });
      },

      //核收窗口关闭跳回原始选择界面
      CollectClose() {
          let that = this;
          let row = that.MasterData.find(e => e.sflag == -1);
          if (!row) {
              if (that.rptunitid == that.BeforePatient.rptunitid && that.selectdate == that.BeforePatient.sampledate) {
                  that.specno = that.BeforePatient.sampleno + "";
                  if (!that.specno) that.specno = "1";
                  that.$parent.QueryList(1);
              } else {
                  that.$parent.QueryList(1);
              }
              that.previousPatient = {};
              that.MasterData = [];
              that.dialogCollectVisible = false;
              that.$emit("update:visible", false);
          } else {
              that.$alert("仍有错误消息未处理!请处理完错误信息再关闭!", "提示");
              that.$emit("update:visible", true);
              that.dialogCollectVisible = true;
          }
      },

      //报告单元改变
      collectrptunitidchange(rptunitid) {
          let that = this;
          if (rptunitid == that.collectrptunitid) return;
          that.MasterData = [];
          that.previousPatient = {};
          that.$tool
              .request({
                  url: "LIS/LIS3/LIS310",
                  method: "post",
                  data: {
                      action: "getreceivesampleno",
                      rptunitid: rptunitid,
                      sampledate: that.collectselectdate,
                      sampleno: "1"
                  }
              })
              .then(res => {
                  if (res.flag == 1) {
                     // that.collectsampleno = res.sampleno;
                     that.collectsampleno = "";
                      if (res.batchinputshownoseg > 0) {
                          that.batchinputshownoseg = true;
                          that.tableColumnBatch = [];
                          for (let i = 0; i < res.RData.Cols.length; i++) {
                              if (res.RData.Cols[i].field == "pat_typename" || res.RData.Cols[i].field == "specimen_name") that.tableColumnBatch.push({ field: res.RData.Cols[i].field, title: res.RData.Cols[i].title, width: "120px" });
                              else that.tableColumnBatch.push({ field: res.RData.Cols[i].field, title: res.RData.Cols[i].title, width: "80px" });
                          }
                          that.tableDataBatch = res.RData.Data;
                      } else {
                          that.batchinputshownoseg = false;
                      }
                      that.CollectNum = 0;
                      that.CollectErrNum = 0;
                  } else {
                      that.$parent.ErrorListDeal(res.msg, res.flag);
                  }
              });
      },

      //主表根据sflag显示不同颜色
      xTableCollect_rowClass({ seq, row, rowIndex, $rowIndex }) {
          if (row.sflag) {
              switch (row.sflag) {
                  case 1:
                      return "processingcls";
                  case -1:
                      return "errocls parent-row";
                  case 2:
                      return "erroalreadyread parent-row";
              }
          }
      },

      //核收前确认提醒
      ValidateBarcode(barcode) {
          return new Promise((s, f) => {
              let that = this;
              that.$tool
                  .request({
                      url: "LIS/LIS3/LIS310",
                      method: "post",
                      data: {
                          action: "reqdetailbybarcode",
                          barcode: barcode
                      }
                  })
                  .then(res => {
                      if (res.errcode == "1") {
                          that.$confirm("当前核收条码号: " + res.showbarcode + " 姓名: " + res.patname + " 标本类型: " + res.specimen + " 申请项目: " + res.reqitem, "提示", {
                              confirmButtonText: "确定",
                              cancelButtonText: "取消",
                              focusCancelButton: true,
                              closeOnClickModal: false,
                              dangerouslyUseHTMLString: true,
                              type: "warning"
                          })
                              .then(() => {
                                  s();
                              })
                              .catch(() => {
                                  f();
                              });
                      } else {
                          this.$alert(res.errmsg, "提示");
                          f();
                      }
                  })
                  .catch(err => {
                      f();
                  });
          });
      },
      //打印核收条码清单
      PrintBarcode() {
          var data = XE.clone(this.$refs.xTableCollect.afterFullData, true);
          if (data.length == 0) {
              this.$alert("没有待打印的核收标本!", "提示");
              return;
          }
          var rptunitname = "";
          var unit = this.$refs.collectrptunit.fulldata.Data.find(item => item.rptunitid == this.collectrptunitid);
          if (unit) rptunitname = unit.rptunitname;
          var sampledate = XE.toDateString(this.collectselectdate, "yyyy-MM-dd");
          let column = this.$refs.xTableCollect.getTableColumn().tableColumn;
          column.push({ property: "rptunitname", title: "报告单元" });
          column.push({ property: "sampledate", title: "核收日期" });
          for (let i = 0; i < data.length; i++) {
              data[i].rptunitname = rptunitname;
              data[i].sampledate = sampledate;
              if (data[i].emer_flag == "1") data[i].emer_flag = "急";
              else data[i].emer_flag = "";
          }
          let str = JSON.stringify(this.$pub.InitColumn(column));
          str += "\r";
          str += JSON.stringify(data);
          let sql = btoa(encodeURIComponent(str));
          jsObj.PrintCustomJsonReport(this.Options.inputsampleliststyle, sql, this.$tool.getSession(this.$tool.loginuserno), "打印清单", "");
          //jsObj.SetCustomJsonPrintConfig(this.Options.inputsampleliststyle, sql, this.$tool.getSession(this.$tool.loginuserno), "打印清单");
      },
      querydata(){
          this.$tool
          .request({
                  url: "LIS/LIS3/LIS310",
              method: "post",
              data: {
                  action: "getbatchbarcode",
                  begindt: this.search_begindt,
                  enddt:this.search_enddt,
                  hospcode:this.search_hoscode,
                  barcodes:this.search_barcodes,
                  rptunitid:this.collectrptunitid,
              },
          })
          .then((res) => {
              this.MasterDataDisplay = res.data;
              res.data.forEach((item) => {
                          this.$nextTick(() => {
                              this.$refs.xTableCollect.setSelection(item, true);
                          });
                      });
          })
          .catch((err) => {

          });
      },
      importPackageBarcode() {
          this.ImportPackageBarcodeVisible = true;
          this.packagebarcode = "";
      },
      ConfirmBarcode() {
          this.$tool
              .request({
                  url: "LIS/LIS3/LIS310",
                  method: "post",
                  data: {
                      action: "getpackagebarcode",
                      packagebarcode: this.packagebarcode,
                  },
              })
              .then((res) => {
                  this.ImportPackageBarcodeVisible = false;
                  if(res.flag == 1) {
                      console.log(res.masters);
                      if(res.masters && res.masters.length > 0){
                          this.MasterDataDisplay = res.masters;
                          res.masters.forEach((item) => {
                                  this.$nextTick(() => {
                                      this.$refs.xTableCollect.setSelection(item, true);
                                  });
                              });
                      } else {
                          this.MasterDataDisplay = [];
                      }

                      if(res.retMsg && res.retMsg.errorMsg.length > 0) {
                          this.tableDataMsgDialog = res.retMsg.errorMsg;
                          this.dialogMsgListVisible = true;
                      }
                  } else {
                      this.$alert(res.msg, "错误");
                  }
              })
              .catch((err) => {

              });
      },
      CancelBarcode() {
          this.ImportPackageBarcodeVisible = false;
          this.packagebarcode = "";
      },
     async confirmInput(){
          let that = this;
          // 确认提交
           let tabledata = this.$refs.xTableCollect.getSelectRecords();
           for( const item of tabledata){
               const element = item;
               let csamplenosync = that.collectsampleno;
               that.CollectSpecType = element.specimen_code;
              const res= await that.BarCodeToServer(that, element.barcode, csamplenosync)
              that.BarCodeServerBack(that, element.barcode, csamplenosync, res, element,false);
               }
      },
       //发送条码请求到服务器
      BarCodeToServer(that, barcodestr, csampleno) {
          that.$pub.Log("核收条码请求开始");
          return that.$tool.request({
              url: "LIS/LIS3/LIS310",
              method: "post",
              data: {
                  action: "inputbarcode",
                  rptunitid: that.collectrptunitid,
                  barcode: barcodestr,
                  sampledate: that.collectselectdate,
                  sampleno: csampleno,
                  reportuser: that.exactusernoreport,
                  isreceive: 1,
                  specimen_code: that.CollectSpecType,
                  alertcannoitem: that.alertcannoitem ? "1" : "0"
              }
          });
      },

      BarCodeServerBack(that, barcodestr, csampleno, res, row,t_issync) {
          if (res.flag == 1) {
              that.MasterData.splice(0, 0, res.report);
              that.$refs.xTableCollect.setCurrentRow(res.report);
              that.previousPatient = res.report;
              that.collectsampleno = res.nextsmpno;
              that.CollectNum = that.MasterData.length;
              this.$refs.xTableCollect.remove(row);
              // if (res.barcode && res.barcodeprintcount && res.barcodeprintcount > 0) {
              //     for (let i = 0; i < res.barcodeprintcount; i++) {
              //         this.RePrintBarcode(res.barcode);
              //     }
              // }
          } else {
                  that.DealEvent(that, barcodestr, res, false, csampleno, res);
          }
      },
  }
};
</script>
<style scoped>
table tr td:nth-child(odd) {
  text-align: right;
  white-space: nowrap;
}
table tr td:nth-child(even) {
  text-align: left;
}
table tr td:nth-child(1) {
  width: 80px;
}
table {
  font-size: 12px;
  border-collapse: separate;
  /* border-spacing: 5px; */
}
/deep/.processingcls td {
  color: #1087ba;
}
/deep/.errocls td {
  color: red;
}
/deep/.erroalreadyread td {
  color: #0a5fb4;
}
.barcoderunning::-webkit-input-placeholder {
  color: #ff0000;
}
/deep/ .parent-row .vxe-cell {
  width: 100% !important;
}
::v-deep .collectspec .el-input__inner {
  font-weight: bold;
  color: blue;
  font-size: 18px;
}
.parent-row-name {
  display: inline-block;
  text-align: left;
  font-weight: 600;
  font-size: 12px;
}
.top-sample-info {
  font-weight: bold;
  font-size: 13px;
  margin-right: 30px;
}

::v-deep .el-input--suffix .el-input__inner {
  padding-right: 20px;
}

::v-deep .collectbtntable .el-checkbox__label {
  padding-left: 2px;
}
</style>
